package org.xiaoleng.igateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.xiaoleng.igateway.security.TokenProvider;
import reactor.core.publisher.Mono;

import java.util.Arrays;

@Component
@Slf4j
public class TokenGatewayFilter implements GlobalFilter, Ordered {

    @Autowired
    private TokenProvider tokenProvider;

    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Value("${jwt.header}")
    private String jwtHeader;

    @Value("${jwt.token-start-with}")
    private String tokenStartWith;

    @Value("${jwt.app-token-start-with}")
    private String appTokenStartWith;

    @Value("${jwt.white-list}")
    private String whiteList;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        if (Arrays.stream(whiteList.split(",")).anyMatch(pattern -> pathMatcher.match(pattern, path))) {
            return chain.filter(exchange);
        }

        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.get(jwtHeader).get(0).replace(appTokenStartWith, "").replace(tokenStartWith, "").trim();
        if (tokenProvider.validateToken(token)) {
            return chain.filter(exchange);
        }

        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
